import json
import os
from flask import Blueprint, request, jsonify, render_template

import applications.view.plugin
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from mod.fun import dir_and_file_tree

dir_path = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")

bp = Blueprint('dev_form', __name__,
               template_folder='templates',
               static_folder='static',
               static_url_path='/dev/static',
               url_prefix='/dev/admin/formbuilder')

@bp.route('/')
def index():
    return render_template('admin/formbuilder/formbuilder.html')

@bp.route('/add')
def add():
    return render_template('admin/formbuilder/add.html')



@bp.route('/filelist', methods=['GET'])
@authorize('dev:admin:form:filelist')
def filelist():
    srcpath = 'etc/forms/sets/'
    if os.path.isdir(srcpath):
        data = dir_and_file_tree(srcpath, [])
        return table_api(msg="成功", data=data)
    else:
        return fail_api(msg="目录不存在")

@bp.route('/conf', methods=['GET', 'POST'])
@authorize('dev:admin:form:conf')
def conf():
    formid = request.form.get('formid')
    appdir = formid.split('-')[0]
    srcpath = 'etc/forms/conf/' + str(appdir) + '/' + str(formid) + '.json'
    if os.path.isfile(srcpath):
        with open(srcpath, 'r', encoding='utf-8') as f:
            data = f.read()
            return table_api(msg="成功", data=data)
    else:
        return fail_api(msg="文件不存在")

@bp.route('/save', methods=['POST'])
@authorize('dev:admin:form:save')
def save():
    formid = request.form.get('formid')
    if '-' not in formid:
        return fail_api(
            msg="请按照 插件目录-表单名称(dev-formname) 的命名方式来命名表单。\r\n说明：插件目录为plugins目录下插件目录名称，后面表单名称为在本应用下templates目录下的模版文件名。")
    tmp = formid.split('-')
    appdir = tmp[0]
    filename = tmp[-1]
    del (tmp[0], tmp[-1])
    dstpath = 'plugins/' + str(appdir)
    if not os.path.isdir(dstpath):
        return fail_api(msg="插件目录不存在")
    templatepath = os.path.join(dstpath, 'templates', *tmp)
    if not os.path.isdir(templatepath):
        os.makedirs(templatepath)
    dstfile = os.path.join(templatepath, filename + '.html')
    dstjsfile = os.path.join(templatepath, filename + '_js.html')
    atempath = '/'.join(tmp) + '/' + filename + '_js.html'
    htmldata = request.form.get('htmldata')
    if htmldata == '':
        return fail_api(msg="表单内容空。")
    formname = request.form.get('formname')
    formaction = request.form.get('formaction')
    formmethod = request.form.get('formmethod')
    if not os.path.exists(dstjsfile):
        # 创建自定义脚本
        myjscode = '''<script>
                    layui.config(
        		{base: "/dev/static/formbuilder/ayq/modules/"}).use(["layer", "laytpl", "element", "form", "slider", "laydate", "rate", "colorpicker", "layedit", "carousel", "upload", "formField", "numberInput", "iconPicker", "cron", "labelGeneration"], function () {
                var $ = layui.jquery
                    , layer = layui.layer
                    , laytpl = layui.laytpl
                    , setter = layui.cache
                    , element = layui.element
                    , slider = layui.slider
                    , laydate = layui.laydate
                    , rate = layui.rate
                    , colorpicker = layui.colorpicker
                    , carousel = layui.carousel
                    , form = layui.form
                    , upload = layui.upload
                    , layedit = layui.layedit
                    , formField = layui.formField
                    , hint = layui.hint
                    , numberInput = layui.numberInput
                    , iconPicker = layui.iconPicker
                    , cron = layui.cron
                    , labelGeneration = layui.labelGeneration;

                //这里写你的代码
            });
        </script>
                '''
        with open(dstjsfile, 'w', encoding='utf-8') as f:
            f.write(myjscode)
    if htmldata.find(dstjsfile) == -1:
        # 如果目的文件不存在，创建空白文件
        if atempath[0] == '/':
            atempath = atempath[1:]
        htmldata = htmldata.replace('</body>', '{% include "' + atempath + '" %}</body>')

    # 插入提交表单的代码。
    jscode = '''<script>
                layui.config(
        {base: "/dev/static/formbuilder/ayq/modules/"}).use(['form', 'jquery','formDesigner'], function () {
                let form = layui.form
                let $ = layui.jquery
                let formDesigner = layui.formDesigner
                form.on('submit(submitform)', function (data) {
                //formdata = formDesigner.getFormData();
                console.log(data.field);
                $.ajax({
                    url: '%s',
                    data: data.field,
                    type: '%s',
                    success: function (result) {
                        if (result.success) {
                            layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                                parent.render()
                            })
                        } else {
                            layer.msg(result.msg, {icon: 2, time: 1000})
                        }
                    }
                });
                return false
            });
            });
                </script>''' % (formaction, formmethod)
    htmldata = htmldata.replace('</body>', jscode + '</body>')
    # import htmlmin
    # htmldata = htmlmin.minify(htmldata, remove_comments=True, remove_empty_space=True)
    # 创建模版文件
    fp = open(dstfile, 'w', encoding='utf-8')
    fp.write(htmldata)
    fp.close()

    jsondata = request.form.get('jsondata')
    etcjsonconfdir = 'etc/forms/conf/' + str(appdir)
    etcjsonsetdir = 'etc/forms/sets/' + str(appdir)
    if not os.path.isdir(etcjsonconfdir):
        os.makedirs(etcjsonconfdir)
    if not os.path.isdir(etcjsonsetdir):
        os.makedirs(etcjsonsetdir)

    dstconffile = etcjsonconfdir + '/' + str(formid) + '.json'
    dstjson = etcjsonsetdir + '/' + str(formid) + '.json'
    fp = open(dstjson, 'w', encoding='utf-8')
    fp.write(jsondata)
    fp.close()
    with open(dstconffile, 'w', encoding='utf-8') as f:
        json.dump({
            'formname': formname,
            'formaction': formaction,
            'formmethod': formmethod,
            'formid': formid,
            'formjson': jsondata
        }, f)
    return success_api(msg="保存成功")

@bp.route('/load', methods=['GET','POST'])
def load():
    formid = request.form.get('formid')
    appdir = formid.split('-')[0]
    srcpath = 'etc/forms/sets/' + str(appdir) + '/' + str(formid) + '.json'
    if os.path.isfile(srcpath):
        with open(srcpath, 'r', encoding='utf-8') as f:
            data = f.read()
            return table_api(msg="成功", data=data)
    else:
        return fail_api(msg="文件不存在")

@bp.route('/cut', methods=['GET','POST'])
def cut():
    formid = request.form.get('formid')
    tmp = formid.split('-')
    appdir = tmp[0]
    filename = tmp[-1]
    del (tmp[0], tmp[-1])
    dstpath = 'plugins/' + appdir
    templatepath = os.path.join(dstpath, "templates", *tmp)
    if not os.path.isdir(templatepath):
        os.makedirs(templatepath)
    etcjsonconfdir = 'etc/forms/conf/' + str(appdir)
    etcjsonsetdir = 'etc/forms/sets/' + str(appdir)
    dstconffile = etcjsonconfdir + '/' + str(formid) + '.json'
    dstjson = etcjsonsetdir + '/' + str(formid) + '.json'
    if os.path.isfile(dstconffile):
        os.remove(dstconffile)
    if os.path.isfile(dstjson):
        os.remove(dstjson)
    return fail_api(msg="表单已经解除关联。")